package com.situ.student.dao.impl;

import com.situ.student.common.Global;
import com.situ.student.dao.SubjectDao;
import com.situ.student.model.Student;
import com.situ.student.model.Subject;
import com.situ.student.util.Pagination;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;

public class SubjectDaoImpl implements SubjectDao {
    private final RowMapper<Subject> rowMapper = new BeanPropertyRowMapper<>(Subject.class);
    public List<Subject> findAll(Pagination pagination, Subject subject){
        JdbcTemplate  jdbcTemplate = Global.getJdbcTemplate();
        List<Object> args = new ArrayList<>();
        String select = "select id,name,description from t_subject";
        StringBuilder where = new StringBuilder();
        where.append(" where 1=1");
        if (subject != null && StringUtils.hasText(subject.getName())) {
            where.append(" and name like ?");
            args.add("%" + subject.getName() + "%");
        }
        //查询记录总数
        String countSql = "select count(0) from (" + select + where + ") t";
        //记录总数
        Long count = jdbcTemplate.queryForObject(countSql, Long.class, args.toArray());
        pagination.setTotal(count);//设置总记录数

        //分页查询sql

        String limitSql = select + where + " limit ?,?";
        args.add(pagination.getOffset());
        args.add(pagination.getLimit());

        //执行查询操作
        List<Subject> list = jdbcTemplate.query(limitSql, rowMapper, args.toArray());
        return list;
    }

    public int deleteByIds(int id){
        JdbcTemplate jdbcTemplate = Global.getJdbcTemplate();
        String sql = "delete from t_subject where id = ?";
        int rows = jdbcTemplate.update(sql, id);
        return rows;
    }

    public int save(Subject subject){
        JdbcTemplate jdbcTemplate = Global.getJdbcTemplate();
        String sql = "insert into t_subject(name,description) values(?,?)";
        int rows = jdbcTemplate.update(sql, subject.getName(), subject.getDescription());
        return rows;
    }
    public int update(Subject subject){
        JdbcTemplate jdbcTemplate = Global.getJdbcTemplate();
        String sql = "update t_subject set name = ?,description = ? where id = ?";
        int rows = jdbcTemplate.update(sql, subject.getName(), subject.getDescription(), subject.getId());
        return rows;
    }
    public Subject findById(Integer id){
        JdbcTemplate jdbcTemplate = Global.getJdbcTemplate();
        String sql = "select id,name,description from t_subject where id = ?";
        Subject subject = jdbcTemplate.queryForObject(sql, rowMapper, id);
        return subject;
    }

}
